import { listByAsync, saveListByAsync } from "@/utils/utools/DbStorageUtil";
import { Url } from "$/entity";
import LocalNameEnum from "@/enumeration/LocalNameEnum";
import { Result } from "$/shared";
import { clientInstanceService } from "@/service";
import { useSnowflake } from "$/util";

export const WebAdapterForUrl: Record<string, Function> = {
  "/api/url/list": async () => {
    const res = await listByAsync<Url>(LocalNameEnum.DB_URL);
    return Result.success(res.list.sort((a, b) => b.sequence! - a.sequence!));
  },
  "/api/url/add": async (url: Url) => {
    const res = await listByAsync<Url>(LocalNameEnum.DB_URL);

    const target: Url = {
      ...url,
      id: useSnowflake().nextId(),
      created_at: Date.now(),
      updated_at: Date.now()
    };

    res.list.push(target);

    const next = await saveListByAsync(LocalNameEnum.DB_URL, res.list, res.rev);

    if (!url.value) {
      // 没有设置链接
      const info = await clientInstanceService.info(target.id);
      url.version = info.version.number;
    }
    await saveListByAsync(LocalNameEnum.DB_URL, res.list, next);

    return Result.success();
  },
  "/api/url/update": async (url: Url) => {
    const res = await listByAsync<Url>(LocalNameEnum.DB_URL);

    const index = res.list.findIndex((item) => item.id === url.id);
    if (index !== -1) {
      res.list[index] = {
        ...res.list[index],
        ...url,
        updated_at: Date.now()
      };
    }

    const next = await saveListByAsync(LocalNameEnum.DB_URL, res.list, res.rev);

    if (!url.value) {
      // 没有设置链接
      const info = await clientInstanceService.info(url.id);
      url.version = info.version.number;
    }

    await saveListByAsync(LocalNameEnum.DB_URL, res.list, next);

    return Result.success();
  },
  "/api/url/delete": async (data: { id: string }) => {
    const res = await listByAsync<Url>(LocalNameEnum.DB_URL);
    await saveListByAsync(
      LocalNameEnum.DB_URL,
      res.list.filter((item) => item.id !== data.id),
      res.rev
    );

    return Result.success();
  }
};
